package com.House_to_rent_System.service;

import com.House_to_rent_System.domain.House;

/**
 * HouseService [业务层]
 * 创建House[]数组，保存House对象
 * 1.响应HouseView的调用
 * 2.完成对房屋信息的各种操作(增删改查（crud）)
 */
public class HouseService {
    private House[] houses;//创建一个House数组
    private int houseNums = 1;
    private int idCounter = 1;

    //创建构造器，传入并定义数组大小
    public HouseService(int size) {
        houses = new House[size];
        houses[0] = new House(1, "jack", "12345", "昌平", 2000, "已出租");
    }

    //调用list方法返回house数组信息
    public House[] list() {
        return houses;
    }

    //创建add方法，添加新对象，并返回boolean值显示是否添加成功
    public boolean add(House newHouse) {
        //判断是否还可以继续添加,如果数组已满则扩充数组并添加
        if (houseNums == houses.length) {
            //调用新的方法用来扩充数组并添加信息
            addExpansion(newHouse);
            System.out.println("数组已满，已扩容并添加...");
            return true;
        }
        //把newHouse放到创建的House[]中
        houses[houseNums++] = newHouse;
        //id自增长
        newHouse.setId(++idCounter);
        return true;
    }
    public void addExpansion(House newHouse){
        House[] houses1 = new House[houses.length+1];
        for (int i = 0 ; i < houses.length ; i++) {
            houses1[i] = houses[i];
        }
        houses1[houseNums++] = newHouse;
        newHouse.setId(++idCounter);
        houses = houses1;
    }

    public boolean deleteHouse(int houseId){
        //找到要删除房间的对应下标
        int index = -1;
        for (int i = 0 ; i < houseNums; i++) {
            if (houseId == houses[i].getId()){
                 index = i;
                 break;
            }
        }
        if (index == -1){//说明要删除的房间在数组中不存在
            return false;
        }
        for (int i = index ; i < houseNums - 1 ; i++) {
            houses[i] = houses[i+1];
        }
        houses[--houseNums] = null;
        return true;
    }
    //输入编号查找房间
    public House selectHouse(int houseId){

        for (int i = 0 ; i < houseNums ; i++) {
            if (houseId == houses[i].getId()){
                return houses[i];
            }
        }
        return null;
    }

}
